<template>
  <div class="assess-manage-container">
    <el-card shadow="hover" class="mb-4 search-card">
      <template #header>
        <div class="search-header">
          <span class="search-title">评价查询</span>
          <el-button size="small" type="primary" @click="handleSearch">
            <i class="el-icon-search mr-1"></i>搜索
          </el-button>
        </div>
      </template>
      <el-form :model="searchForm" :inline="true" size="small" class="search-form">
        <el-form-item label="商品ID">
          <el-input v-model="searchForm.productId" placeholder="请输入商品ID" clearable size="small" />
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="searchForm.content" placeholder="请输入内容" clearable size="small" />
        </el-form-item>
        <el-form-item label="评分">
          <el-input-number v-model="searchForm.rating" :min="1" :max="5" size="small" />
        </el-form-item>
        <el-form-item label="状态" style="width: 150px;">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable size="small">
            <el-option label="全部" :value="null" />
            <el-option label="已发布" :value="1" />
            <el-option label="隐藏" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="default" @click="resetForm">
            <i class="el-icon-refresh mr-1"></i>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="hover" class="table-card">
      <el-table :data="tableData" border stripe fit highlight-current-row class="custom-table">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="productId" label="商品ID" min-width="100" align="center" />
        <el-table-column prop="content" label="内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="rating" label="评分" min-width="80" align="center" />
        <el-table-column prop="isAnonymous" label="匿名" min-width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.isAnonymous ? 'info' : 'success'">{{ row.isAnonymous ? '是' : '否' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="80" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.status === 1" type="success">已发布</el-tag>
            <el-tag v-else-if="row.status === 2" type="danger">隐藏</el-tag>
            <el-tag v-else-if="row.status === 3" type="warning">已删除</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="200" align="center">
          <template #default="{ row }">
            {{ row.createTime ? dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="hideReason" label="隐藏原因" min-width="120" show-overflow-tooltip />
        <el-table-column label="操作" min-width="220" align="center" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleHide(row)"
              :disabled="row.status === 2 || row.status === 3"
            >
              隐藏
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="handleDelete(row)"
              :disabled="row.status === 3"
            >
              删除
            </el-button>
            <el-button
              type="success"
              link
              size="small"
              @click="handleViewAddition(row)"
              :disabled="row.status === 3"
            >
              追评
            </el-button>
            <el-button type="warning" link size="small" @click="handleViewDetail(row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="table-pagination">
        <div class="text-sm text-gray-500">共 {{ total }} 条数据</div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          prev-text="上一页"
          next-text="下一页"
        />
      </div>
    </el-card>
    <el-dialog v-model="additionDialogVisible" title="追评信息" width="900px" :close-on-click-modal="false">
      <el-table :data="additionList" border stripe fit>
        <el-table-column prop="evaluationId" label="追评ID" min-width="80" align="center" />
        <el-table-column prop="content" label="内容" min-width="200" />
        <el-table-column prop="rating" label="评分" min-width="80" align="center" />
        <el-table-column prop="status" label="状态" min-width="80" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.status === 1" type="success">已发布</el-tag>
            <el-tag v-else-if="row.status === 2" type="danger">隐藏</el-tag>
            <el-tag v-else-if="row.status === 3" type="warning">已删除</el-tag>
            <el-tag v-else type="default">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="160" align="center">
          <template #default="{ row }">
            {{ row.createTime ? dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') : '' }}
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="additionDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="detailDialogVisible" title="评价详情" width="600px" :close-on-click-modal="false">
      <div v-if="detailRow">
        <div class="detail-row"><b>评价ID：</b>{{ detailRow.evaluationId }}</div>
        <div class="detail-row"><b>商品ID：</b>{{ detailRow.productId }}</div>
        <div class="detail-row"><b>内容：</b>{{ detailRow.content }}</div>
        <div class="detail-row"><b>评分：</b>{{ detailRow.rating }}</div>
        <div class="detail-row"><b>匿名：</b>{{ detailRow.isAnonymous ? '是' : '否' }}</div>
        <div class="detail-row"><b>状态：</b>
          <el-tag v-if="detailRow.status === 1" type="success">已发布</el-tag>
          <el-tag v-else-if="detailRow.status === 2" type="danger">隐藏</el-tag>
          <el-tag v-else-if="detailRow.status === 3" type="danger">删除</el-tag>
        </div>
        <div class="detail-row"><b>创建时间：</b>{{ detailRow.createTime ? dayjs(detailRow.createTime).format('YYYY-MM-DD HH:mm:ss') : '' }}</div>
        <div class="detail-row"><b>图片：</b>
          <div v-if="detailImages.length">
            <el-image v-for="(img, idx) in detailImages" :key="idx" :src="img" style="width:80px;height:80px;margin-right:8px;" :preview-src-list="detailImages" />
          </div>
          <span v-else>无</span>
        </div>
        <div class="detail-row"><b>视频：</b>
          <div v-if="detailVideos.length">
            <video v-for="(vid, idx) in detailVideos" :key="idx" :src="vid" style="width:120px;height:80px;margin-right:8px;" controls />
          </div>
          <span v-else>无</span>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="hideDialogVisible" title="隐藏评价" width="500px">
      <el-form-item label="隐藏原因">
        <el-input v-model="hideReason" type="textarea" :rows="3" placeholder="请输入隐藏原因" />
      </el-form-item>
      <template #footer>
        <el-button @click="hideDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmHide">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getAdminAssessList,
  hideAdminAssess,
  deleteAdminAssess,
  getAdditionalsByEvaluationId,
  getAdminAdditionPage,
  getAssessDetail
} from '@/api/assess'
import dayjs from 'dayjs'

const searchForm = reactive({
  pageNum: 1,
  pageSize: 10,
  productId: '',
  content: '',
  rating: null,
  isAnonymous: '',
  status: null
})
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])
const additionDialogVisible = ref(false)
const additionList = ref([])
const detailDialogVisible = ref(false)
const detailRow = ref(null)
const detailImages = ref([])
const detailVideos = ref([])
const hideDialogVisible = ref(false)
const hideReason = ref('')
const currentItemToHide = ref(null)

const fetchData = async () => {
  try {
    const params = { ...searchForm, pageNum: currentPage.value, pageSize: pageSize.value }
    const res = await getAdminAssessList(params)
    if (res && (res.code === 0 || res.code === 200) && res.data) {
      const records = res.data.records || []
      total.value = res.data.total || 0

      // Concurrently fetch details for each assessment
      const detailPromises = records.map(async (record) => {
        try {
          const detailRes = await getAssessDetail(record.evaluationId)
          if (detailRes && (detailRes.code === 0 || detailRes.code === 200) && detailRes.data) {
            const medias = Array.isArray(detailRes.data) ? detailRes.data : [detailRes.data].filter(Boolean)
            record.images = medias.filter(m => m && m.mediaType === 1).map(m => m.mediaUrl)
            record.videos = medias.filter(m => m && m.mediaType === 2).map(m => m.mediaUrl)
          } else {
            record.images = []
            record.videos = []
          }
        } catch (e) {
          console.error(`Failed to fetch details for evaluationId ${record.evaluationId}`, e)
          record.images = []
          record.videos = []
        }
        return record
      })

      tableData.value = await Promise.all(detailPromises)
    } else {
      ElMessage.error(res.msg || '获取数据失败')
    }
  } catch (e) {
    ElMessage.error('获取数据失败')
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}
const resetForm = () => {
  searchForm.productId = ''
  searchForm.content = ''
  searchForm.rating = null
  searchForm.isAnonymous = ''
  searchForm.status = null
  currentPage.value = 1
  fetchData()
}
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}
const handleHide = (row) => {
  currentItemToHide.value = row
  hideReason.value = ''
  hideDialogVisible.value = true
}
const confirmHide = async () => {
  if (!currentItemToHide.value) return
  if (!hideReason.value) {
    ElMessage.warning('请输入隐藏原因')
    return
  }
  try {
    const params = {
      evaluationId: currentItemToHide.value.evaluationId,
      status: 2,
      hideReason: hideReason.value
    }
    const res = await hideAdminAssess(params)
    if (res && (res.code === 0 || res.code === 200)) {
      ElMessage.success('隐藏成功')
      hideDialogVisible.value = false
      fetchData()
    } else {
      ElMessage.error(res.msg || '隐藏失败')
    }
  } catch (e) {
    ElMessage.error('隐藏失败')
  }
}
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '您确定要删除此商品下的所有评价吗？此操作将永久删除数据。',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    const res = await deleteAdminAssess(row.evaluationId)
    if (res && (res.code === 0 || res.code === 200)) {
      ElMessage.success('删除成功')
      if (tableData.value.length === 1 && currentPage.value > 1) {
        currentPage.value = currentPage.value - 1
      }
      fetchData()
    } else {
      ElMessage.error('删除操作失败')
    }
  } catch (e) {
    ElMessage.error('删除操作失败')
  }
}
const handleViewAddition = async (row) => {
  try {
    const res = await getAdditionalsByEvaluationId(row.evaluationId)
    if (res && (res.code === 0 || res.code === 200)) {
      additionList.value = res.data || []
      additionDialogVisible.value = true
    } else {
      ElMessage.error(res.msg || '获取追评信息失败')
    }
  } catch (e) {
    ElMessage.error('获取追评信息失败')
  }
}
const handleViewDetail = (row) => {
  detailRow.value = row
  detailImages.value = row.images || []
  detailVideos.value = row.videos || []
  detailDialogVisible.value = true
}
onMounted(fetchData)
</script>

<style scoped>
.assess-manage-container {
  padding: 24px 32px;
  background: #f6f8fa;
  min-height: 100vh;
}
.search-card {
  margin-bottom: 18px;
  border-radius: 8px;
}
.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.search-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}
.search-form {
  margin-top: 8px;
}
.table-card {
  border-radius: 8px;
}
.custom-table {
  font-size: 15px;
  background: #fff;
  border-radius: 8px;
}
.table-pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 18px;
}
.el-table th {
  background: #f2f3f5;
  color: #333;
  font-weight: 500;
}
.el-table .el-button {
  padding: 0 6px;
}
.detail-row {
  margin-bottom: 12px;
  font-size: 15px;
}
</style> 